<template>
  <div class="big-box">
    <div class="order-seach-box">
      <div class="ticketList-top-btn">
        <el-button @click="goBack()" style="width:160px" icon="el-icon-arrow-left">返回</el-button>
        <el-tag type="info">表单名称：{{$route.params.formName}}</el-tag>
        <el-button :loading="loadingRelease" type="primary" @click="releaseForm()" style="width:160px" icon="el-icon-check">确定发布</el-button>
      </div>
    </div>
    <div v-loading="loadingTable" element-loading-text="拼命加载中" class="order-con-box">
      <div class="form-left ">
        <el-button @click="addTem(item)" v-for="(item,index) of fieldCodeList" :key="index" style="width:146px; margin: 6px 0px;" plain>{{item.colcomment}}</el-button>
        <!-- <el-button @click="addTem(item,'ext','stringTem')" v-if="extList.length" style="width:146px; margin: 6px 0px;" plain>自定义字符类型</el-button> -->
        <!-- <el-button @click="addTem(item,'ext','moreSelectTem')" v-if="extList.length" style="width:146px; margin: 6px 0px;" plain>自定义多菜单类型</el-button> -->
      </div>
      <div ref="formCenter" id="formCenter" class="form-center">
        <draggable style="width:100%" v-model="templateList" :options="{disabled:false}">
          <div :class="{'thisEditTrm':thisEditTemId==item.temId}" @click="setTem(item)" @mouseover="item.isShowDel=true" @mouseout="item.isShowDel=false" v-for="(item ,index) of templateList" :key="index" class="template-container">
            <component @setTem="setTem" :thisComponen="item" :is="'stringTem'"></component>
            <el-button @click.stop="delTem(item.temId)" v-if="thisEditTemId==item.temId&&item.attribute.filedCode!='uName'&&item.attribute.filedCode!='uTel'" class="template-container-del" icon="el-icon-delete" size="mini"></el-button>
          </div>
        </draggable>
        <div v-if="templateList.length>=8" style="width:100%;height:66px"></div>
      </div>
      <div class="form-right">
        <stringTemCon v-if="setThisTemplate.attribute" :setThisTemplate="setThisTemplate"></stringTemCon>
      </div>
    </div>
  </div>
</template>
<script>
import draggable from "vuedraggable"; //拖动组建
// 组件
import stringTem from "./comTemple/stringTem";

// json
import templateJson from "./json/template.json";

// 组件控件
import stringTemCon from "./temSetCon/stringTemCon";

// 验证提交表单的数据
import { checkTemplateList } from "./js/checkTemplateList.js";
// 检验是否具有相同的字段编码
import { checkField } from "./js/checkField.js";

import service from "@/api/fieldManagementBox";

import country from "./../form/json/country.json";
import {
  t_industry,
  t_sacle,
  t_job,
  t_gender,
  t_province,
  t_constellation,
  typeOfCertificate
} from "./js/utils.js";

// import componenList from "./js/testJson";
export default {
  components: {
    draggable,
    stringTem,
    stringTemCon
  },
  data() {
    return {
      loadingTable: false, //表格
      extList: [], //自定义扩展字段
      fieldCodeList: [], // 确定字段编码数据
      templateList: [], //渲染的模板
      loadingRelease: false,
      thisEditTemId: "", //当前编辑的模板id
      setThisTemplate: {} //设置当前的组件
    };
  },
  created() {
    this.initFun();
  },
  methods: {
    async initFun() {
      this.loadingTable = true;
      const { data = [] } = await service.getModel({
        vtable: "yunxi_ticket"
      }); // 获取字段编码
      this.loadingTable = false;
      this.fieldCodeList = data;
      // this.extList = []; //自定义扩展字段
      // this.fieldCodeList = []; //确定字段编码数据
      // for (let i = 0; i < data.length; i++) {
      //   // 自定义扩展字段和确定字段编码数据做区分
      //   let reg = RegExp(/ext/);
      //   if (reg.test(data[i].columnname)) {
      //     this.extList.push(data[i]);
      //   } else {
      //     this.fieldCodeList.push(data[i]);
      //   }
      // }
      let componenList = [];
      if (this.$route.params.componenList) {
        componenList = JSON.parse(this.$route.params.componenList);
      }
      if (componenList.length) {
        console.log(componenList);

        // 如果是编辑
        componenList.map(item => {
          let obj = {
            temId: Number(new Date()) + Math.random(),
            isShowDel: false,
            ...item
          };
          if (!obj.attribute.maxLength) {
            this.$set(obj.attribute, "maxLength", 360);
          }
          if (!obj.attribute.selectList) {
            this.$set(obj.attribute, "selectList", []);
          }
          if (!obj.attribute.changeTemType) {
            this.$set(obj.attribute, "changeTemType", false);
          }
          if (item.componentName == "moreSelectTem") {
            obj.attribute.changeTemType = true;
          }
          this.templateList.push(JSON.parse(JSON.stringify(obj)));
          this.watchFieldCode();
        });
      } else {
        //默认添加一些必填字段
        this.addTem({
          colcomment: "使用人名称",
          columnname: "uName",
          datatype: "varchar"
        });

        this.addTem({
          colcomment: "使用人手机号",
          columnname: "uTel",
          datatype: "varchar"
        });
      }

      setTimeout(() => {
        this.setTem(this.templateList[0]);
      }, 1000);
    },
    // 添加组件
    addTem(fieldCode) {
      let item = {
        componentName: "stringTem",
        attribute: {
          filedValue: "",
          filedCode: "",
          titName: "字段标题",
          placeholder: "请输入",
          maxLength: 360,
          ifCheck: true,
          selectList: []
        }
      };
      item.temId = Number(new Date()) + Math.random();
      item.isShowDel = false;
      item.attribute.titName = fieldCode.colcomment;
      item.attribute.filedCode = fieldCode.columnname;
      item.attribute.selectList = [];
      item.attribute.filedValue = "";
      this.$set(item.attribute, "changeTemType", false); //是否需要下拉菜单(即是否需要将字符类型改成选择类型)
      if (fieldCode.columnname == "country") {
        this.$alert(
          "建议将“国籍”字段移至第一行!考虑到对“手机号”字段长度的影响。",
          "提示",
          {
            confirmButtonText: "确定",
            callback: action => {}
          }
        );
        item.attribute.filedValue = "中国大陆";
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        country.data.map(it => {
          item.attribute.selectList.push({
            name: it.name,
            ifSel: false
          });
        });
      }

      if (fieldCode.columnname == "industry") {
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        item.attribute.selectList = t_industry;
      }
      if (fieldCode.columnname == "scale") {
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        item.attribute.selectList = t_sacle;
      }
      if (fieldCode.columnname == "job") {
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        item.attribute.selectList = t_job;
      }
      if (fieldCode.columnname == "gender") {
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        item.attribute.selectList = t_gender;
      }
      if (fieldCode.columnname == "province") {
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        item.attribute.selectList = t_province;
      }

      if (fieldCode.columnname == "typeOfCertificate") {
        item.attribute.changeTemType = true;
        item.componentName = "moreSelectTem";
        item.attribute.selectList = typeOfCertificate;
        item.attribute.filedValue = "居民身份证";
        //如果选择了证件类型
        for (let i = 0; i < this.fieldCodeList.length; i++) {
          if (this.fieldCodeList[i].columnname == "country") {
            const it = this.fieldCodeList[i];
            setTimeout(() => {
              this.addTem(it);
            }, 1000);
          }
        }
      }
      this.templateList.push(JSON.parse(JSON.stringify(item)));

      this.watchFieldCode();
      this.scrollBot();
    },
    //删除组件
    delTem(temId) {
      for (let i = 0; i < this.templateList.length; i++) {
        if (temId == this.templateList[i].temId) {
          this.fieldCodeList.push({
            colcomment: this.templateList[i].attribute.titName,
            columnname: this.templateList[i].attribute.filedCode,
            datatype: "varchar"
          });
          this.templateList.splice(i, 1);
        }
        if (temId == this.thisEditTemId) {
          this.setThisTemplate = {};
          this.setTem(this.templateList[0]);
        }
      }
    },
    // 监听字段是否已被添加，如果添加则左边进行删除
    watchFieldCode() {
      for (let i = 0; i < this.templateList.length; i++) {
        for (let j = 0; j < this.fieldCodeList.length; j++) {
          if (
            this.templateList[i].attribute.filedCode ==
            this.fieldCodeList[j].columnname
          ) {
            this.fieldCodeList.splice(j, 1);
          }
        }
      }
    },
    // 检测滚动到指定位置
    scrollBot() {
      if (this.templateList.length >= 8) {
        this.$refs.formCenter.scrollTop = (this.templateList.length - 8) * 84;
      }
    },
    // 设置组件
    setTem(item) {
      this.setThisTemplate = item;
      this.thisEditTemId = item.temId;
    },
    goBack() {
      this.$router.go(-1);
    },
    // 提交字段表单
    subFieldFrom(subData) {
      let subDataObj = {
        tableName: this.$route.params.formName,
        vtable: "yunxi_ticket",
        activityId: this.$store.state.activityId,
        componenList: subData
      };
      let api = "/api/isv/temp/saveModel";
      if (this.$route.params.id != "") {
        api = "/api/isv/temp/editModelCard";
        subDataObj.id = this.$route.params.id;
      }
      this.loadingRelease = true;
      subDataObj.isPay = "pay";
      this.$http.post(api, subDataObj).then(
        res => {
          this.loadingRelease = false;
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "数据提交成功!"
            });
            this.goBack();
          } else {
            this.$message({
              message: res.data.errorMsg || "数据提交失败",
              type: "warning"
            });
          }
        },
        err => {
          this.loadingRelease = false;
          this.$message.error("服务器出小差了");
        }
      );
    },
    // 发布表单
    async releaseForm() {
      if (this.templateList.length == 0) {
        this.$message({
          message: "请进行表单配置",
          type: "warning"
        });
        return;
      }
      let subData = await checkTemplateList(this.templateList);
      if (subData) {
        // 检验是否具有相同的字段编码
        let subDataResult = await checkField(subData);
        if (!subDataResult) {
          // 检测到字段编码具有相同的
          this.$confirm("检测到表单多个字段同时使用同一个字段,请确定", "提示", {
            confirmButtonText: "我知道了",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {})
            .catch(() => {});
        } else {
          this.subFieldFrom(subData);
        }
      }
    }
  }
};
</script>

<style scoped>
.big-box {
  width: 100%;
  height: auto;
}
.order-seach-box {
  width: 100%;
  height: auto;
  background: #fff;
  border-radius: 6px;
  padding: 26px;
}
.ticketList-top-btn {
  width: 100%;
  height: auto;
  margin: 0px 0px;
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-align-items: center;
  align-items: center;
}
.order-con-box {
  width: 100%;
  height: auto;
  min-height: 200px;
  background: #fff;
  border-radius: 6px;
  padding: 26px;
  /* margin-top: 18px; */
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-align-items: flex-start;
  align-items: flex-start;
}
.form-left {
  width: 180px;
  min-height: 300px;
  max-height: 600px;
  overflow-y: auto;
  height: auto;
  border: 1px solid #ebebeb;
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-align-items: center;
  align-items: center;
  flex-wrap: wrap;
  border-radius: 6px;
  padding: 10px 0px;
}

.form-left:hover {
  box-shadow: 0px 0px 8px rgba(237, 237, 236, 0.6);
}
.form-center {
  width: 46%;
  border: 1px solid #ebebeb;
  min-height: 300px;
  height: auto;
  max-height: 600px;
  overflow-y: auto;
  border-radius: 6px;
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-align-items: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  padding: 26px;
}
.form-center:hover {
  box-shadow: 0px 0px 8px rgba(237, 237, 236, 0.6);
}
.form-right {
  width: 400px;
  min-height: 300px;
  max-height: 600px;
  overflow-y: auto;
  height: auto;
  border: 1px solid #ebebeb;
  border-radius: 6px;
  padding: 26px;
}
.form-right:hover {
  box-shadow: 0px 0px 8px rgba(237, 237, 236, 0.6);
}
.template-container {
  width: 100%;
  height: auto;
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-align-items: center;
  align-items: center;
  /* margin-bottom: 16px; */
  padding: 16px 6px 16px 0px;
  border: 1px dashed #fff;
  position: relative;
}
.template-container:hover {
  border: 1px solid #ebebeb;
  cursor: pointer;
  box-shadow: 0px 0px 8px rgba(237, 237, 236, 0.6);
}
.thisEditTrm {
  border: 1px solid #00b2a9 !important;
  box-shadow: 0px 0px 8px rgba(237, 237, 236, 0.6);
}
.template-container-del {
  position: absolute;
  right: 12px;
  top: 22px;
}
</style>
